#include "mainwindow.h"
#include "ui_mainwindow.h"
#include<QNetworkInterface>
static int iCountReviceMsg = 0;

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    //设置标题
    setWindowTitle("TCP调试助手 v1.0");
    //窗口大小尺寸设计
    setFixedSize(width(),height());
    //多行文本编辑框设置为只读属性
    ui->plainTextEdi_msgList->setReadOnly(true);
    //设置光标位置
    ui->plainTextEdit_sendMsg->setFocus();
    //默认发送的测试文本消息
    ui->plainTextEdit_sendMsg->setPlainText("Hello TCP Server/Client");
    ui->comboBox_ipAdr->setEditable(true);

    ui->comboBox_ipAdr->setEditText("192.168.232.1");



    connect(ui->radioButton_server,&QRadioButton::toggled,this,&MainWindow::serverButtonStateFunc);
    connect(ui->radioButton_client,&QRadioButton::toggled,this,&MainWindow::clientButtonStateFunc);
    ui->radioButton_server->setChecked(true);



    //初始化操作
    tcpServer = new QTcpServer(this);
    //connect(tcpServer,&QTcpServer::newConnection,this,&MainWindow::tcpServerConnected);


    QList<QHostAddress> addrList = QNetworkInterface::allAddresses();
    foreach(const QHostAddress &address,addrList)
    {
        if(address.protocol() == QAbstractSocket::IPv4Protocol)
        {
            ui->comboBox_ipAdr->addItem(address.toString());
        }
    }

}





MainWindow::~MainWindow()
{
    delete ui;
}


//监听服务
void MainWindow::on_toolButton_start_clicked()
{
    QHostAddress address = QHostAddress(ui->comboBox_ipAdr->currentText());
    int port = ui->spinBox_port->text().toInt();
    //检测ip的合法性
    QString strIpAdrs = ui->comboBox_ipAdr->currentText();
    if(checkIpAddressIsVaild(strIpAdrs) == false)
    {
        QMessageBox::critical(this,"Error","Error Prompt:" + strIpAdrs + "\n" + "Illegal IP address,please recheck?"
                              ,QMessageBox::Yes);
        ui->comboBox_ipAdr->setFocus();
        return;
    }


    //检查服务器是否正在监听
    if(tcpServer->isListening())
    {
        tcpServer->close();
        for(auto client:tcpSocketList)
        {
            client->close();
        }
        tcpSocketList.clear();
        ui->plainTextEdi_msgList->appendPlainText(QString("[Prompt]:Successfully monitored %1:%2")
                                                  .arg(address.toString()).arg(port));

    }
    else
    {
        if(!tcpServer->listen(address,port))
        {
            ui->plainTextEdi_msgList->clear();
            ui->plainTextEdi_msgList->appendPlainText(QString("[Prompt]:listening failed,Please check the IP and port."));
        }
        else
        {
            //监听成功
            ui->plainTextEdi_msgList->clear();
            ui->plainTextEdi_msgList->appendPlainText(QString("[Prompt]:server listening successfully(%1:%2).")
                                                      .arg(address.toString()).arg(port));
            ui->toolButton_start->setEnabled(false);
            ui->toolButton_close->setEnabled(true);

            //创建 连接套接字tcpSocket
            connect(tcpServer,&QTcpServer::newConnection,this,&MainWindow::newConnection);



        }
    }



}

//关闭监听
void MainWindow::on_toolButton_close_clicked()
{
    tcpServer->close();
    for(auto client:tcpSocketList)
    {
        client->close();
    }
    tcpSocketList.clear();
    ui->plainTextEdi_msgList->appendPlainText(QString("[Prompt]:Disconnnect all client connections."));
    ui->toolButton_start->setEnabled(true);
    ui->toolButton_close->setEnabled(false);
}

//连接服务器
void MainWindow::on_toolButton_connect_clicked()
{
    //连接服务器之前，数据信息要全部清除
    ui->plainTextEdi_msgList->clear();

    ui->toolButton_connect->setEnabled(false);
    ui->toolButton_disconnect->setEnabled(true);

    //获取用户所选的ip和端口
    QString ipAdr = ui->comboBox_ipAdr->currentText();
    int port = ui->spinBox_port->text().toInt();

    //检测Ip地址合法性
    if(checkIpAddressIsVaild(ipAdr) == false)
    {
        QMessageBox::critical(this,"Error","Error Prompt:" + ipAdr + "\n" + "Illegal IP address,please recheck?"
                              ,QMessageBox::Yes);
        ui->comboBox_ipAdr->setFocus();
        return;
    }

    //连接服务器端
    bool isBools = networkClient.clientConnectToServer(ipAdr,port);
    if(isBools == true)
    {
        //服务器连接成功
        ui->plainTextEdi_msgList->clear();
        ui->plainTextEdi_msgList->appendPlainText("[Prompt]:Successfully connected to the Server.");
        //打开自动化测试按钮,客户端自动测试复选按钮可以使用了
        ui->checkBox_clientAutoTest->setEnabled(true);
        ui->toolButton_send->setEnabled(true);
        ui->plainTextEdit_sendMsg->setEnabled(true);
        connect(networkClient.socket,&QTcpSocket::readyRead,this,&MainWindow::readAllData);

    }
    else
    {
        ui->plainTextEdi_msgList->appendPlainText("[Prompt]:Failed connectde to the Server.");
        ui->toolButton_connect->setEnabled(true);
        ui->toolButton_disconnect->setEnabled(false);
        ui->plainTextEdit_sendMsg->setEnabled(true);
    }
}


//断开服务器
void MainWindow::on_toolButton_disconnect_clicked()
{
    ui->toolButton_connect->setEnabled(true);
    ui->toolButton_disconnect->setEnabled(false);
    networkClient.disconnectFromHost();

    //断开服务器连接，开启用户可以输入数据信息
    ui->plainTextEdit_sendMsg->setEnabled(true);
    ui->plainTextEdit_sendMsg->setFocus();

    //获取初始选中的状态
    bool isInitState = ui->checkBox_clientAutoTest->isChecked();
    ui->checkBox_clientAutoTest->setChecked(true);
    ui->checkBox_clientAutoTest->setChecked(isInitState);
    ui->checkBox_clientAutoTest->setChecked(false);
    ui->checkBox_clientAutoTest->setEnabled(false);


    //断开服务器连接，禁止 plainTextEdit_sendMsg 使用
    ui->plainTextEdit_sendMsg->setEnabled(false);
    //断开服务器，发送消息按钮禁用
    ui->toolButton_send->setEnabled(false);

    ui->plainTextEdi_msgList->appendPlainText("[Prompt:Disconnect from Server.]");
}


//发送消息
void MainWindow::on_toolButton_send_clicked()
{
    QString strSendMsg = ui->plainTextEdit_sendMsg->toPlainText();
    if(strSendMsg.isEmpty())
    {
        ui->plainTextEdit_sendMsg->setFocus();
        return;
    }




    //获取当前日期和时间
    QDateTime currentDateTime = QDateTime::currentDateTime();
    QString year = QString::number(currentDateTime.date().year());
    QString month = QString::number(currentDateTime.date().month());
    QString day = QString::number(currentDateTime.date().day());
    QString hour = QString::number(currentDateTime.time().hour());
    QString minute = QString::number(currentDateTime.time().minute());
    QString second = QString::number(currentDateTime.time().second());

    QString strTemp = year + "-" + month + "-" + day + " " + hour + ":"
            + minute + ":" + second;
    QString strTemps;

    //判断是客户端要发送还是服务器要发送消息
    if(ui->radioButton_client->isChecked())
    {
        networkClient.clientSendMsgToServer(strSendMsg);
        strTemps = "\n[" + strTemp + " Sended Client message]:\n" +strSendMsg;
    }
    else if(ui->radioButton_server->isChecked())
    {
        // 服务器发送：遍历所有客户端套接字并发送
        for (QTcpSocket* serverSocket : tcpSocketList) {
            if (serverSocket->isOpen() && serverSocket->state() == QAbstractSocket::ConnectedState) {
                qDebug() << serverSocket;
                int temp = serverSocket->write((strSendMsg + "\n").toUtf8()); // 使用 UTF-8 编码更安全
                 qDebug() << temp;
                strTemps = "\n[" + strTemp + " Sended Server message]:\n" + strSendMsg;
            }
        }
    }

    ui->plainTextEdi_msgList->appendPlainText(strTemps);
    ui->plainTextEdit_sendMsg->clear();
    ui->plainTextEdit_sendMsg->setFocus();

}



//关闭应用程序
void MainWindow::on_toolButton_exit_clicked()
{
    this->close();
}

//检测IP地址是否合法
bool MainWindow::checkIpAddressIsVaild(QString strIpAdress)
{

    if(strIpAdress.isEmpty())
    {
        return false;
    }

    QStringList list = strIpAdress.split('.');
    if(list.size() != 4)
    {
        return false;
    }

    for(const auto &num:list)
    {
        bool ok = false;
        //若num 无法转换,ok = false
        //若num 正常转换,ok = true
        int temp = num.toInt(&ok);
        if(!ok || temp < 0 || temp > 255)
        {
            return false;
        }
    }
    return true;
}

//客户端
void MainWindow::clientButtonStateFunc()
{
    ui->plainTextEdi_msgList->clear();
    ui->toolButton_connect->setEnabled(true);
    ui->plainTextEdit_sendMsg->setEnabled(true);

    ui->toolButton_disconnect->setEnabled(false);
    ui->toolButton_start->setEnabled(false);
    ui->toolButton_close->setEnabled(false);
    //当用户选择客户端单选按钮时，禁止 plainTextEdit 输入
    ui->plainTextEdit_sendMsg->setEnabled(false);

    //防止服务器启动监听之后，用户点击客户端按钮
    ui->plainTextEdi_msgList->clear();
    //关闭TCP套接字，及每一个客户端
    tcpServer->close();
    for(auto client:tcpSocketList)
    {
        client->close();
    }
    tcpSocketList.clear();
}

//服务器
void MainWindow::serverButtonStateFunc()
{
    ui->plainTextEdi_msgList->clear();

    ui->toolButton_connect->setEnabled(false);
    ui->toolButton_disconnect->setEnabled(false);
    ui->plainTextEdit_sendMsg->setEnabled(false);
    ui->toolButton_send->setEnabled(false);

    ui->toolButton_start->setEnabled(true);
    ui->toolButton_close->setEnabled(false);

    //客户端断开连接
    networkClient.disconnect();
    ui->checkBox_clientAutoTest->setChecked(false);
    ui->checkBox_clientAutoTest->setEnabled(false);


    //断开服务器连接，开启用户可输入数据信息
    ui->plainTextEdit_sendMsg->setEnabled(true);
    ui->plainTextEdit_sendMsg->setFocus();

    ui->checkBox_clientAutoTest->setChecked(false);
    //当用户选择客户端，再次切换到服务器单选按钮时，禁止用户输入消息
    ui->plainTextEdit_sendMsg->setEnabled(false);
    networkClient.stopTimerOutFunc();

    //初始化 tcpServer
    tcpServer = new QTcpServer(this);
}


//tcp连接服务
void MainWindow::tcpServerConnected(){}
//{
//    //此处的 tcpSocket 是 明确的新客户端套接字对象，直接来源于服务器的 nextPendingConnection()
//    //,无需通过 sender() 获取
//    tcpSocket = tcpServer->nextPendingConnection();
//    if(!tcpSocketList.contains(tcpSocket))
//    {
//        tcpSocketList.append(tcpSocket);
//    }
//    //连接信号与槽，当tcpSocket中有数据可读时，调用槽函数readAllData
//    connect(tcpSocket,&QTcpSocket::readyRead,this,&MainWindow::readAllData);
//    //连接信号与槽，当tcpSocket断开连接，调用槽函数clientDisconnected
//    connect(tcpSocket,&QTcpSocket::disconnected,this,&MainWindow::clientDisconnected);

//    //tcpSocket->peerPort() 获取 已建立连接的远程对等端（peer）的端口号
//    QString strPort = QString::number(tcpSocket->peerPort());

//    ui->toolButton_send->setEnabled(true);
//    ui->plainTextEdit_sendMsg->setEnabled(true);
//    ui->plainTextEdi_msgList->appendPlainText("\n[Prompt]:New client connection:("+tcpSocket->peerAddress().toString()
//                                              +":"+strPort+")");
//    //有新客户端连接
//    iCountReviceMsg=0;
//}


//断开客户端
void MainWindow::clientDisconnected()
{
    QTcpSocket *client = dynamic_cast<QTcpSocket*>(sender());
    QString strMsg = QString("\n[Prompt]:Client disconnected:(%1:%2)")
            .arg(client->peerAddress().toString()).arg(client->peerPort());
    ui->plainTextEdi_msgList->appendPlainText(strMsg);
}


//读取消息
void MainWindow::readAllData()
{
    QTcpSocket * socket = dynamic_cast<QTcpSocket*>(sender());
    QByteArray buff = socket->readAll();
    buff.chop(1);
    //获取当前日期和时间
    QDateTime currentDateTime = QDateTime::currentDateTime();
    QString year = QString::number(currentDateTime.date().year());
    QString month = QString::number(currentDateTime.date().month());
    QString day = QString::number(currentDateTime.date().day());
    QString hour = QString::number(currentDateTime.time().hour());
    QString minute = QString::number(currentDateTime.time().minute());
    QString second = QString::number(currentDateTime.time().second());

    QString strTemp = year + "-" + month + "-" + day + " " + hour + ":"
            + minute + ":" + second;
    QString strTemps;

    if(ui->radioButton_server->isChecked())
    {
        strTemps = "\n[" + strTemp + " Received server message]:\n" +buff;
    }
    else if(ui->radioButton_client->isChecked())
    {
        strTemps = "\n[" + strTemp + " Received client message]:\n" +buff;
    }

    ui->plainTextEdi_msgList->appendPlainText(strTemps);

    //读取客户端套接字的数据信息，且直接回复 --> 暂时不用
    //    QString strReturnBackTemp = "[Server reply message]:" + buff;
    //    QByteArray qbtReturnBackTemp = QByteArray::fromStdString(strReturnBackTemp.toStdString());
    //    client->write(qbtReturnBackTemp);
}


//等待客户端的连接
void MainWindow::newConnection()
{
    tcpSocket = tcpServer->nextPendingConnection();
    qDebug() << tcpSocket;
    tcpSocketList.append(tcpSocket);

    ui->plainTextEdi_msgList->appendPlainText("[Prompt]:Server and client had connected successfully");
    ui->toolButton_send->setEnabled(true);
    ui->plainTextEdit_sendMsg->setEnabled(true);


    //读取数据连接
    connect(tcpSocket,&QTcpSocket::readyRead,this,&MainWindow::readAllData);

    // 连接断开时自动移除并释放
    connect(tcpSocket, &QTcpSocket::disconnected, [=]() {
        tcpSocketList.removeOne(tcpSocket);
        tcpSocket->deleteLater();
    });



}


//自动测试按钮
void MainWindow::on_checkBox_clientAutoTest_clicked()
{
    bool checkBoxStatus = ui->checkBox_clientAutoTest->isChecked();
    //用户选择客户端自动测试控件
    if(checkBoxStatus == true)
    {
        //启动定时器函数，自动向服务器发送消息
        networkClient.startTimerOutFunc();
        ui->plainTextEdit_sendMsg->setEnabled(false);
        ui->toolButton_send->setEnabled(false);
    }
    else
    {
        networkClient.stopTimerOutFunc();
    }
}

//调用UDP窗口调试模块
#include "udpmodule.h"
void MainWindow::on_toolButton_udpTest_clicked()
{
    UdpModule *udpOject = new UdpModule(this);

    //阻塞之前窗口 运行UDP窗口
    udpOject->exec();
}



// 将文本转换为十六进制
QString MainWindow::stringToHex(const QString &input) {
    QByteArray byteArray = input.toUtf8();
    QString hexString;
    for (char c : byteArray) {
        hexString += QString("%1 ").arg(static_cast<quint8>(c), 2, 16, QLatin1Char('0')).toUpper();
    }
    return hexString.trimmed(); // 移除末尾空格
}


QString MainWindow::hexToString(const QString &hexInput) {
    QByteArray byteArray;
    QStringList hexValues = hexInput.split(" "); // 按空格分割

    for (const QString &hexVal : hexValues) {
        QString cleanHex = hexVal.startsWith("0x") ? hexVal.mid(2) : hexVal; // 移除0x前缀
        bool ok;
        char byte = static_cast<char>(cleanHex.toInt(&ok, 16)); // 转为字节
        if (ok) {
            byteArray.append(byte);
        } else {
            // 错误处理（可选）
            qWarning() << "Invalid hex value:" << hexVal;
        }
    }

    return QString::fromUtf8(byteArray); // UTF-8 解码
}

void MainWindow::on_pushButton_clicked()
{
    QString text = ui->plainTextEdi_msgList->toPlainText(); // 获取输入文本
    QString hex = stringToHex(text);                // 转换为十六进制
    ui->plainTextEdi_msgList->setPlainText(hex);            // 显示结果
}

void MainWindow::on_pushButton_2_clicked()
{
    QString hexText = ui->plainTextEdi_msgList->toPlainText(); // 获取十六进制文本
    QString originalText = hexToString(hexText);        // 转回原始文本
    ui->plainTextEdi_msgList->setPlainText(originalText);      // 显示结果
}
